package com.jt.common.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.common.annotation.RequestLog;
import com.jt.common.exception.ServiceException;
import com.jt.common.utils.IPUtils;
import com.jt.sys.dao.SysLogDao;
import com.jt.sys.entity.SysLog;
import com.jt.sys.entity.SysUser;

@Aspect
@Service
public class SysLogAspect {

	@Autowired
	private SysLogDao sysLogDao;
	@Pointcut("@annotation(com.jt.common.annotation.RequestLog)")
	public void logPointCut(){}
	
	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable{
		System.out.println("++++SysLogAspect+++");
		Long beginTime=System.currentTimeMillis();
		Object result=point.proceed();
		long time=System.currentTimeMillis()-beginTime;
		saveSysLog(point,time);
		System.out.println("hhh");
		return result;
	}

	private void saveSysLog(ProceedingJoinPoint point, long time) {
		MethodSignature signature=(MethodSignature)point.getSignature();
		Method method=signature.getMethod();
		Class<?> classTarget=point.getTarget().getClass();
		Class<?>[] par=signature.getParameterTypes();
		Method targetMethod=null;
		try{
			targetMethod=classTarget.getMethod(method.getName(),par);
		}catch(Exception e){
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
		SysLog sysLog=new SysLog();
		RequestLog requestLog=targetMethod.getAnnotation(RequestLog.class);
		System.out.println("requestLog="+requestLog);
		if(requestLog!=null){
			System.out.println("oper=="+requestLog.value());
			sysLog.setOperation(requestLog.value());
		}
		String className=point.getTarget().getClass().getName();
		String methodName=signature.getName();
		sysLog.setMethod(className+"."+methodName+"()");
		Object[] args=point.getArgs();
		System.out.println(args+"是什么");
		try{
			String params=new ObjectMapper().writeValueAsString(args[0]);
			sysLog.setParams(params);
		}catch(Exception e){
			e.printStackTrace();
		}
		sysLog.setIp(IPUtils.getIpAddr());
		SysUser sysUser=(SysUser)SecurityUtils.getSubject().getPrincipal();
		String username=sysUser.getUsername();
		System.out.println(username);
		sysLog.setUsername(username);
		sysLog.setTime(time);
		
		sysLog.setCreatedTime(new Date((System.currentTimeMillis()+8*60*60*1000)));
		System.out.println(sysLog);
//		保存日志到数据库
		sysLogDao.insertObject(sysLog);
	}
	
	
}
